#include<iostream>
#include<functional>
#include<errno.h>
#include<string.h>
#include"Socket.hpp"
#include"EventLoop_Timequeue.hpp"
#include"Connection.hpp"
#include"Acceptor.hpp"

uint64_t conn_id = 1;//连接id
std::unordered_map<uint64_t,ConnPtr> conn_map;//保存连接的映射表



//通信套接字的回调函数
void ServCloseCallback(const ConnPtr &conn)
{
    conn_map.erase(conn->ConnId());
}
void MsgCallback(const ConnPtr &conn,Buffer *buf)
{
    char buftmp[1024];
    buf->ReadAndMove(buftmp,buf->ReadableSize());
    LOG_DBG("recv msg :%s",buftmp);
    std::string str = "hello world";
    conn->Send(str.c_str(),str.size());//发送消息
}
void ConnectCallback(const ConnPtr &conn)
{
    LOG_INF("new connection %p",conn.get());
}



//服务器监听套接字的回调函数（底层就是accept系统调用）
void AcceptorCallback(EventLoop *loop,int newfd)
{
    LOG_INF("new connection fd:%d",newfd);
    ConnPtr conn = std::make_shared<Connection>(loop,conn_id,newfd);
    //为通信套接字设置回调函数
    conn->SetConnectedCallback(std::bind(ConnectCallback,std::placeholders::_1));
    conn->SetMessageCallback(std::bind(MsgCallback,std::placeholders::_1,std::placeholders::_2));
    conn->EnableInactiveRelease(5);
    conn->SetServerClosedCallback(std::bind(ServCloseCallback,std::placeholders::_1));
    conn->Establish();//启动连接(包含加入监听)
    conn_map[conn_id] = conn;
    conn_id++;
}

int main()
{
    EventLoop loop;//创建事件循环(epoll监听)
    Acceptor acceptot(&loop,8888);  
    acceptot.SetAcceptCallback(std::bind(AcceptorCallback,&loop,std::placeholders::_1));//设置监听套接字的回调函数
    acceptot.Listen();
    while(true){
        loop.Start();//启动事件循环
    }

    return 0;
}


